package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConst;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    JedisPool jedisPool;

    @Reference
    OrderService orderService;

    /**
     * 提交预约信息
     *  步骤：
     *      1. 校验验证码，如果正确，提交，如果错误，返回验证码输出错误
     *      2. 设置预约方式
     *      3. 调用service，添加预约信息
     *      4. 预约成功后，发送预约成功的通知短信给用户
     */
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map<String,String> map){
        //获取手机号
        String telephone = map.get("telephone");

        //校验Redis缓存中的验证码和用户输入的验证码
        String validateCodeInRedis = jedisPool.getResource().get(RedisConst.SENDTYPE_ORDER + "-" + telephone);

        String validateCodeInParam = map.get("validateCode");

        if (!(validateCodeInRedis !=null && validateCodeInRedis.equals(validateCodeInParam))){
            //验证码不正确，返回验证码输入错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        //设置预约方式
        map.put("orderType", Order.ORDERTYPE_WEIXIN);

        //调用service
        Result result = null;
        try {
            result = orderService.addOrder(map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //预约成功后，发送预约成功的通知短信给用户
        if (result.isFlag()){
            //发送预约成功的通知短信给用户
        }

        return result;
    }

    /**
     * 通过ID查询预约数据
     */
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Map<String,Object> resultMap = orderService.findById(id);

            //日期进行转换
            Date orderDate = (Date)resultMap.get("orderDate");
            String orderDateStr = DateUtils.parseDate2String(orderDate);
            resultMap.put("orderDate",orderDateStr);

            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
            
        }

    }


}


